package com.ruoyi.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.INdAlarmRecorderService;
import com.ruoyi.system.service.INdAntiRunningRecorderService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端api集合
 */
@Api("前端api集合")
@RestController
@RequestMapping("/system/indexpage")
public class Nd_IndexPageApiController {
    @Autowired
    private Nd_ApiMapper ad_ApiMapper;
    @Autowired
    private INdAlarmRecorderService ndAlarmRecorderService;
    @Autowired
    private com.ruoyi.system.service.ChangeShiftsRecordService changeShiftsRecordService;
    @Autowired
    private ISysUserService userService;
//    @Autowired
//    private SysDictTypeMapper sysDictTypeMapper;

    @Autowired
    private INdAntiRunningRecorderService indAntiRunningRecorderService;

    @ApiOperation("一个车站所有设备状态")
    @PostMapping("/getFieldsByStationId")
    public List<Nd_Field> getFieldsByStationId(@RequestBody String Station_Id) {
        List<Nd_Field> ndFields = ad_ApiMapper.getFieldsByStationId(Station_Id);
        ndFields.forEach(ndField -> ndField.Tracks.forEach(track -> {
            if (track.qbid != null) {
                List<RLTrainRecoder> rlTrainRecoderList = ad_ApiMapper.selectAntiRunningRecorderByTypeAndTrainId(track.qbid);
                track.rlTrainRecoderList = rlTrainRecoderList;
            }
        }));
        return ndFields;
    }

    @ApiOperation("股道占用信息列表")
    @PostMapping("/getTracksByFieldId")
    public List<Nd_Track> getTracksByFieldId(@RequestBody String Field_Id) {
        List<Nd_Track> ndTrackList = ad_ApiMapper.getTracksByFieldId(Field_Id);
        return ndTrackList;
    }

    @ApiOperation("手动布防:添加车辆信息、布防信息")
    @PostMapping("/addTrainAndDevice")
    @Transactional(rollbackFor = Exception.class)
    public boolean addTrainAndDevice(@RequestBody Nd_TrainAndDevice nd_TrainAndDevice) {
        //添加车辆信息,即股道占用情况
        String loginUser = SecurityUtils.getUsername();
        nd_TrainAndDevice.nd_trainRecoder.create_by = loginUser;
        if (StrUtil.isNotEmpty(nd_TrainAndDevice.nd_trainRecoder.qbid)) {
            ad_ApiMapper.updateTrainRecoder(nd_TrainAndDevice.nd_trainRecoder);
        } else {
            ad_ApiMapper.insertTrainRecorder(nd_TrainAndDevice.nd_trainRecoder);
        }
        //更新设备实时状态表
        nd_TrainAndDevice.nd_devicesWrokStatus.Inbox_Id = "0";
        ad_ApiMapper.updateDeviceStatus(nd_TrainAndDevice.nd_devicesWrokStatus);
        //添加防溜台账
        Nd_AntiRunningRecorder devAnti = new Nd_AntiRunningRecorder();
        devAnti.Station_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Station_Id;
        devAnti.Track_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Track_Id;
        devAnti.Device_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Device_Id;
        devAnti.Railway_CarNo = nd_TrainAndDevice.nd_devicesWrokStatus.Railway_CarNo;
        devAnti.SortNo = nd_TrainAndDevice.nd_devicesWrokStatus.SortNo;
        devAnti.Postion = nd_TrainAndDevice.nd_devicesWrokStatus.Postion;
        devAnti.Work_Type_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Work_Type_Id;
        devAnti.Person_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Person_Id;
        devAnti.Operation_Type_Id = nd_TrainAndDevice.nd_devicesWrokStatus.Operation_Type_Id;
        devAnti.qbid = nd_TrainAndDevice.nd_trainRecoder.qbid;
        devAnti.create_by = loginUser;
        devAnti.create_time = String.valueOf(java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
        devAnti.update_by = loginUser;
        devAnti.update_time = String.valueOf(java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
        devAnti.placement_time = nd_TrainAndDevice.nd_devicesWrokStatus.placement_time;
        ad_ApiMapper.insertAntiRunningRecorder(devAnti);
        //添加人力制动机
        if (CollectionUtil.isNotEmpty(nd_TrainAndDevice.nd_trainRecoder.rlTrainRecoderList)) {
            nd_TrainAndDevice.nd_trainRecoder.rlTrainRecoderList.forEach(rlTrainRecoder -> {
                rlTrainRecoder.qbid = nd_TrainAndDevice.nd_trainRecoder.qbid;
                rlTrainRecoder.Track_Id = nd_TrainAndDevice.nd_trainRecoder.Track_Id;
                rlTrainRecoder.Station_Id = nd_TrainAndDevice.nd_trainRecoder.Station_Id;
            });
            indAntiRunningRecorderService.addLZDJ(nd_TrainAndDevice.nd_trainRecoder.rlTrainRecoderList);
        }
//        indAntiRunningRecorderService.addOrUpdateRLZDJ(nd_TrainAndDevice.rlTrainRecoderList);
        //通知前端页面
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        Nd_DevicesWrokStatus inoutTimeDeviceStatus = nd_TrainAndDevice.nd_devicesWrokStatus;
        if (inoutTimeDeviceStatus.Work_Type_Id.equals("1")) {
            inoutTimeDeviceStatus.out_time = null;
            inoutTimeDeviceStatus.in_time = null;
            ndAlarmRecorderService.updateAlaerStatus(4, Integer.parseInt(inoutTimeDeviceStatus.Device_Id)
                    , Integer.parseInt(inoutTimeDeviceStatus.Station_Id), inoutTimeDeviceStatus.Device_VIN);
            ndAlarmRecorderService.updateAlaerStatus(5, Integer.parseInt(inoutTimeDeviceStatus.Device_Id)
                    , Integer.parseInt(inoutTimeDeviceStatus.Station_Id), inoutTimeDeviceStatus.Device_VIN);
        } else {
            inoutTimeDeviceStatus.out_time = null;
            inoutTimeDeviceStatus.in_time = LocalDateTime.now().toString();
        }
        ad_ApiMapper.updateInOutTimeStatus2(inoutTimeDeviceStatus);
        myWebSocketHandler.sendMessage("devChange");
        return true;
    }

    @ApiOperation("更新设备状态: 例如修改车辆号、顺位号、防溜人、撤防等")
    @PostMapping("/updateDeviceWorkStatus")
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDeviceWorkStatus(@RequestBody Nd_DevicesWrokStatus nd_devicesWrokStatus) {
        //更新设备实时状态表
        String loginUser = SecurityUtils.getUsername();
        nd_devicesWrokStatus.update_by = loginUser;
//        Nd_AntiRunningRecorder ndAntiRunningRecorder = BeanCopyUtils.copyBean(nd_devicesWrokStatus, Nd_AntiRunningRecorder.class);
        Nd_AntiRunningRecorder ndAntiRunningRecorder = new Nd_AntiRunningRecorder();
        ndAntiRunningRecorder.Station_Id = nd_devicesWrokStatus.Station_Id;
        ndAntiRunningRecorder.Track_Id = nd_devicesWrokStatus.Track_Id;
        ndAntiRunningRecorder.Device_Id = nd_devicesWrokStatus.Device_Id;
        ndAntiRunningRecorder.Railway_CarNo = nd_devicesWrokStatus.Railway_CarNo;
        ndAntiRunningRecorder.SortNo = nd_devicesWrokStatus.SortNo;
        ndAntiRunningRecorder.Postion = nd_devicesWrokStatus.Postion;
        ndAntiRunningRecorder.Work_Type_Id = nd_devicesWrokStatus.Work_Type_Id;
        ndAntiRunningRecorder.Person_Id = nd_devicesWrokStatus.Person_Id;
        ndAntiRunningRecorder.Operation_Type_Id = nd_devicesWrokStatus.Operation_Type_Id;
        ndAntiRunningRecorder.qbid = nd_devicesWrokStatus.qbid;
        ndAntiRunningRecorder.create_by = loginUser;
        ndAntiRunningRecorder.create_time = String.valueOf(java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
        ndAntiRunningRecorder.update_by = loginUser;
        ndAntiRunningRecorder.update_time = String.valueOf(java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
        ndAntiRunningRecorder.placement_time = nd_devicesWrokStatus.placement_time;
        //更新防溜记录信息
        if (nd_devicesWrokStatus.Work_Type_Id.equals("1")) {
            //修改防溜台账
            ad_ApiMapper.updateAntiRunningRecorder(ndAntiRunningRecorder);
            ad_ApiMapper.updateDeviceStatus(nd_devicesWrokStatus);
        } else {
            //新增撤防防溜台账
            ad_ApiMapper.insertAntiRunningRecorder(ndAntiRunningRecorder);
            nd_devicesWrokStatus.Track_Id = "0";
            nd_devicesWrokStatus.Postion = "0";
            nd_devicesWrokStatus.Person_Id = "0";
            nd_devicesWrokStatus.Railway_CarNo = "0";
            nd_devicesWrokStatus.SortNo = "0";
            nd_devicesWrokStatus.no_box_state="撤防";
            ad_ApiMapper.updateDeviceStatus(nd_devicesWrokStatus);
        }
        if (nd_devicesWrokStatus.Work_Type_Id.equals("1")) {
            nd_devicesWrokStatus.out_time = null;
            nd_devicesWrokStatus.in_time = null;
            ndAlarmRecorderService.updateAlaerStatus(4, Integer.parseInt(nd_devicesWrokStatus.Device_Id)
                    , Integer.parseInt(nd_devicesWrokStatus.Station_Id), nd_devicesWrokStatus.Device_VIN);
            ndAlarmRecorderService.updateAlaerStatus(5, Integer.parseInt(nd_devicesWrokStatus.Device_Id)
                    , Integer.parseInt(nd_devicesWrokStatus.Station_Id), nd_devicesWrokStatus.Device_VIN);
        } else {
            nd_devicesWrokStatus.out_time = null;
            nd_devicesWrokStatus.in_time = LocalDateTime.now().toString();
        }
        ad_ApiMapper.updateInOutTimeStatus2(nd_devicesWrokStatus);
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        myWebSocketHandler.sendMessage("devChange");
        return true;
    }

    @ApiOperation("修改车辆: 例如修改车辆号、车次、车型描述、发车等")
    @PostMapping("/updateTrainRecorder")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateTrainRecorder(@RequestBody Nd_TrainRecoder nd_TrainRecoder) {
        String loginUser = SecurityUtils.getUsername();
        if (nd_TrainRecoder.dfbz.equals("2")) { //如果是发车，需要添加接发车记录
            nd_TrainRecoder.create_by = loginUser;
            ad_ApiMapper.insertTrainRecorder(nd_TrainRecoder);
        } else {                                  //修改车辆信息，仅更新记录即可
            nd_TrainRecoder.update_by = loginUser;
            ad_ApiMapper.updateTrainRecoder(nd_TrainRecoder);
            indAntiRunningRecorderService.addLZDJ(nd_TrainRecoder.rlTrainRecoderList);
        }
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        myWebSocketHandler.sendMessage("trackChange");
        return AjaxResult.success();
    }

    @ApiOperation("根据部门查用户") //用来实现选择防溜人
    @PostMapping("/getUsersByStationId")
    public List<Nd_User> getUsersByStationId(@RequestBody UserStation userStation) {
        System.out.println(userStation);
        List<Nd_User> ndUserList = ad_ApiMapper.getUsersByStationId(userStation.getStationId(), userStation.getPost_id(), userStation.getIs_on_guard());
        return ndUserList;
    }

    @ApiOperation("添加车辆")
    @PostMapping("/addTrainRecorder")
    @Transactional(rollbackFor = Exception.class)
    public boolean addTrainRecorder(@RequestBody @Valid Nd_TrainRecoder nd_TrainRecoder) {
        String loginUser = SecurityUtils.getUsername();
        nd_TrainRecoder.create_by = loginUser;
        ad_ApiMapper.insertTrainRecorder(nd_TrainRecoder);
        if (CollectionUtil.isNotEmpty(nd_TrainRecoder.rlTrainRecoderList)) {
            nd_TrainRecoder.rlTrainRecoderList.forEach(rlTrainRecoder -> {
                rlTrainRecoder.qbid = nd_TrainRecoder.qbid;
                rlTrainRecoder.Track_Id = nd_TrainRecoder.Track_Id;
                rlTrainRecoder.Station_Id = nd_TrainRecoder.Station_Id;
            });
            indAntiRunningRecorderService.addLZDJ(nd_TrainRecoder.rlTrainRecoderList);
        }
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        myWebSocketHandler.sendMessage("trackChange");
        return true;
    }

    @ApiOperation("人力制动机撤防")
    @PostMapping("/removeSz")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult removeSz(@RequestBody List<RLTrainRecoder> rlTrainRecoderList) {
        //修改车辆手闸开启标记
        String qbid = rlTrainRecoderList.get(0).qbid;
        ad_ApiMapper.updateTrainIsOpen(qbid);
        //修改布防的防溜台账 is_remove 置0
        ad_ApiMapper.updateAntiRunningIsRemove(qbid);
        //添加撤防的防溜台账
        rlTrainRecoderList.forEach(rlTrainRecoder -> {
            rlTrainRecoder.Anti_Recorder_Id = null;
            rlTrainRecoder.Work_Type_Id = 2;
        });
        indAntiRunningRecorderService.addOrUpdateRLZDJ(rlTrainRecoderList);
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        myWebSocketHandler.sendMessage("trackChange");
        return AjaxResult.success();
    }


    @ApiOperation("手动入箱出箱子")
    @PostMapping("/manual/operation")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult manualOperation(@RequestBody Nd_DevicesWrokStatus nd_devicesWrokStatus) {
        if (nd_devicesWrokStatus.Inbox_Id.equals("0")) {
            nd_devicesWrokStatus.in_time = null;
            nd_devicesWrokStatus.out_time = LocalDateTime.now().toString();
            nd_devicesWrokStatus.no_box_state ="出箱";
            ndAlarmRecorderService.updateAlaerStatus(10, Integer.valueOf(nd_devicesWrokStatus.Device_Id)
                    , Integer.parseInt(nd_devicesWrokStatus.Station_Id), nd_devicesWrokStatus.Device_VIN);
        } else {
            nd_devicesWrokStatus.in_time = null;
            nd_devicesWrokStatus.out_time = null;
            //如果是入箱子解决报警
            ndAlarmRecorderService.updateAlaerStatus(5, Integer.parseInt(nd_devicesWrokStatus.Device_Id)
                    , Integer.parseInt(nd_devicesWrokStatus.Station_Id), nd_devicesWrokStatus.Device_VIN);
            ndAlarmRecorderService.updateAlaerStatus(4, Integer.parseInt(nd_devicesWrokStatus.Device_Id)
                    , Integer.parseInt(nd_devicesWrokStatus.Station_Id), nd_devicesWrokStatus.Device_VIN);
        }
        ad_ApiMapper.updateInOutTimeStatus2(nd_devicesWrokStatus);
        ad_ApiMapper.manualOperationUpdateDeviceStatus(nd_devicesWrokStatus);
        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
        myWebSocketHandler.sendMessage("trackChange");
        //加上入箱出箱时间
        return AjaxResult.success();
    }

    //    @ApiOperation("语音报警")
    @PostMapping("/voice/alarm")
    public AjaxResult voiceAlarm(@RequestBody String Station_Id) {

        //查询报警记录，10S之内的  需要去重，去重后返回 对应的报警信息需要
        List<Nd_AlarmRecorder> ndAlarmRecorders = ad_ApiMapper.selectVoiceAlarm(Station_Id)
                .stream().distinct().collect(Collectors.toList());
        return AjaxResult.success(ndAlarmRecorders);
    }

    @PostMapping("/voice/alarm2")
    public AjaxResult voiceAlarm2(@RequestBody String Station_Id) {

        //查询报警记录，10S之内的  需要去重，去重后返回 对应的报警信息需要
        List<Nd_AlarmRecorder> ndAlarmRecorders = ad_ApiMapper.selectVoiceAlarm2(Station_Id)
                .stream().distinct().collect(Collectors.toList());
        return AjaxResult.success(ndAlarmRecorders);
    }

    @GetMapping("/shifting/of/query/{Station_Id}")
    public AjaxResult shiftingOfQuery(@PathVariable String Station_Id) {
        System.out.println(Station_Id);
        //查询车站所有设备
        List<Nd_DevicesWrokStatus> deviceAll = ad_ApiMapper.selectAllDevByStationId(Station_Id);
        //查询报警信息
        List<Nd_AlarmRecorder> ndAlarmRecorders = ad_ApiMapper.selectVoiceAlarm2(Station_Id)
                .stream().distinct().collect(Collectors.toList());
        //查看是否有设备存在失联报警
        List<String> missingDeviceIds = ndAlarmRecorders.stream().filter(n -> n.Alarm_Type.equals("3")).map(a -> a.Device_Id).collect(Collectors.toList());
        //查询每个类型的设备有多少失联的
        Map<String, Integer> missingDevNum = new HashMap<>();
        if (CollectionUtil.isNotEmpty(missingDeviceIds)){
            missingDevNum = ad_ApiMapper.selectMissingDevnum(missingDeviceIds);
        }
        //根据设备类型分组
        Map<String, List<Nd_DevicesWrokStatus>> typeDev = deviceAll.stream().collect(Collectors.groupingBy(d -> d.Device_Type));
        ArrayList<DeviceNum> r = new ArrayList<>();
        Map<String, Integer> finalMissingDevNum = missingDevNum;
        typeDev.forEach((type, list) -> {
            if (type.equals("2") || type.equals("3") || type.equals("5")) {
                DeviceNum deviceNum = new DeviceNum();
                deviceNum.setType(type);
                deviceNum.setAllDev(list.size());
                //deviceNum.setOnBoxDev(list.stream().filter(d -> !d.Inbox_Id.equals("0") && d.Inbox_Id != null).collect(Collectors.toList()).size());
                if (type.equals("2")) {
                    deviceNum.setOnBoxDev(list.stream().filter(d -> !d.Inbox_Id.equals("0") && d.Inbox_Id != null).collect(Collectors.toList()).size());
                    deviceNum.setNoBoxDev(list.stream().filter(d -> d.Inbox_Id.equals("0") && d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                } else {
                    deviceNum.setOnBoxDev(list.stream().filter(d -> d.Inbox_Id.equals("0") && d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                    deviceNum.setNoBoxDev(0);
                }
                deviceNum.setIndev(list.stream().filter(d -> !d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                if (finalMissingDevNum.containsKey(type)) {
                    deviceNum.setMissingNum(finalMissingDevNum.get(type));
                }
                r.add(deviceNum);
            }
        });
        return AjaxResult.success(DeviceNumAlarm.builder().alarms(ndAlarmRecorders).deviceNums(r).build());
    }


    @PostMapping("/shifting/log/detail")
    public AjaxResult shiftingLogDetail(@RequestBody UserStation userStation) {
        List<Nd_DevicesWrokStatus> deviceAll = ad_ApiMapper.selectshiftingLogDetail(userStation.getChangeShiftsId());

        //查询报警信息
        List<Nd_AlarmRecorder> ndAlarmRecorders = ad_ApiMapper.selectVoiceAlarmByShiftsId(userStation.getChangeShiftsId())
                .stream().distinct().collect(Collectors.toList());
        //查看是否有设备存在失联报警
        List<String> missingDeviceIds = ndAlarmRecorders.stream().filter(n -> n.Alarm_Type.equals("3")).map(a -> a.Device_Id).collect(Collectors.toList());
        //查询每个类型的设备有多少失联的
        Map<String, Integer> missingDevNum = new HashMap<>();
        if (CollectionUtil.isNotEmpty(missingDeviceIds)){
            missingDevNum = ad_ApiMapper.selectMissingDevnum(missingDeviceIds);
        }


        Map<String, List<Nd_DevicesWrokStatus>> typeDev = deviceAll.stream().collect(Collectors.groupingBy(d -> d.Device_Type));
        ArrayList<DeviceNum> r = new ArrayList<>();
        Map<String, Integer> finalMissingDevNum = missingDevNum;
        typeDev.forEach((type, list) -> {
            if (type.equals("2") || type.equals("3") || type.equals("5")) {
                DeviceNum deviceNum = new DeviceNum();
                deviceNum.setType(type);
                deviceNum.setAllDev(list.size());
                //deviceNum.setOnBoxDev(list.stream().filter(d -> !d.Inbox_Id.equals("0") && d.Inbox_Id != null).collect(Collectors.toList()).size());
                if (type.equals("2")) {
                    deviceNum.setOnBoxDev(list.stream().filter(d -> !d.Inbox_Id.equals("0") && d.Inbox_Id != null).collect(Collectors.toList()).size());
                    deviceNum.setNoBoxDev(list.stream().filter(d -> d.Inbox_Id.equals("0") && d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                } else {
                    deviceNum.setOnBoxDev(list.stream().filter(d -> d.Inbox_Id.equals("0") && d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                    deviceNum.setNoBoxDev(0);
                }
                deviceNum.setIndev(list.stream().filter(d -> !d.Track_Id.equals("0")).collect(Collectors.toList()).size());
                if (finalMissingDevNum.containsKey(type)) {
                    deviceNum.setMissingNum(finalMissingDevNum.get(type));
                }
                r.add(deviceNum);
            }
        });
        return AjaxResult.success(DeviceNumAlarm.builder().alarms(ndAlarmRecorders).deviceNums(r).build());
    }


    /**
     * 提交交接班
     *
     * @param changeShiftsRecord
     * @return
     */
    @PostMapping("/add/shifting/of/duty")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult shiftingOfDuty(@RequestBody ChangeShiftsRecord changeShiftsRecord) {
        System.out.println(changeShiftsRecord);
//        if (changeShiftsRecord.getJiaoban_lkrlist().isEmpty()){
//            return AjaxResult.error("500","交班联控人不能为空！");
//        }else if (changeShiftsRecord.getJieban_lklist().isEmpty()){
//            return AjaxResult.error("500","接班联控人不能为空！");
//        }else if (changeShiftsRecord.getHandover_Personslist().isEmpty()){
//            return AjaxResult.error("500","交班防溜人不能为空！");
//        }else if (changeShiftsRecord.getTakeover_Personslist().isEmpty()){
//            return AjaxResult.error("500","接班防溜人不能为空！");
//        }
        //添加一个记录表
        changeShiftsRecordService.insert(changeShiftsRecord);
        //查询车站的所有设备信息
        List<Nd_DevicesWrokStatus2> deviceAll = ad_ApiMapper.selectAllDevByStationId2(String.valueOf(changeShiftsRecord.getStationId()));
        //把设备信息存到记录表中
        List<NdChangeShiftsDetail> ndChangeShiftsDetails = BeanCopyUtils.copyBeanList(deviceAll, NdChangeShiftsDetail.class);
        //把报警信息保存
        if (!changeShiftsRecord.getAlarmIds().isEmpty()) {
            ad_ApiMapper.updateAlarmAddShiftsId(changeShiftsRecord.getAlarmIds(), changeShiftsRecord.getChange_Shifts_Id());
        }
        //添加关联外键
        ndChangeShiftsDetails.forEach(n -> n.setChange_Shifts_Id(changeShiftsRecord.getChange_Shifts_Id()));
        //存入记录数据中
        ad_ApiMapper.addndChangeShiftsDetails(ndChangeShiftsDetails);
//        //修改用户岗位
//        List<Long> handover_personslist = changeShiftsRecord.Handover_Personslist1();
//        handover_personslist.addAll(changeShiftsRecord.Jiaoban_lkrlist1());
//        List<Long> takeover_personslist = changeShiftsRecord.Takeover_Personslist1();
//        takeover_personslist.addAll(changeShiftsRecord.Jieban_lklist1());
        //handover_personslist改成休息
        userService.updateUserState(changeShiftsRecord.Jiaoban_lkrlist1(), 0);
        //takeover_personslist改为在岗
        userService.updateUserState(changeShiftsRecord.Jieban_lklist1(), 1);

        return AjaxResult.success();
    }


    @PostMapping("/shifting/of/log")
    public AjaxResult2 shiftingOfLog(@RequestBody PageR<ChangeShiftsRecord> param) {
        return changeShiftsRecordService.query(param);
    }

//    @ApiOperation("根据场查询铁鞋") //暂时不用了
//    @PostMapping("/getDevicesByField")
//    public List<Nd_DevicesWrokStatus> getDevicesByField(@RequestBody String Field_Id) {
//        List<Nd_DevicesWrokStatus> boxArr = new ArrayList<>();
//        List<Nd_DevicesWrokStatus> shoesArr = new ArrayList<>();
//        List<Nd_DevicesWrokStatus> freeShoesArr = new ArrayList<>();
//
//        boxArr = ad_ApiMapper.getDevicesByFiled(Field_Id, "4");
//        shoesArr = ad_ApiMapper.getDevicesByFiled(Field_Id, "2");
//
//        Map<String, Nd_DevicesWrokStatus> boxMap = new HashMap<>();
//        for(Nd_DevicesWrokStatus box : boxArr) {
//            boxMap.put(box.Device_Id, box);
//        }
//
//        Nd_DevicesWrokStatus freeBox = new Nd_DevicesWrokStatus();
//        freeBox.Device_Id = "0";
//        freeBox.Device_Type = "99999999";
//        freeBox.Device_Code = "游离区";
//        freeBox.Shoes = freeShoesArr;
//
//        for (Nd_DevicesWrokStatus shoe : shoesArr) {
//            if (shoe.Inbox_Id.equals("0")) {
//                freeShoesArr.add(shoe); // 所属班级为 0 的学生放入单独的集合
//            } else {
//                Nd_DevicesWrokStatus box = boxMap.get(shoe.Inbox_Id);
//                if (box != null) {
//                    box.Shoes.add(shoe); // 将学生分配到对应的班级
//                }
//            }
//        }
//        boxArr.add(freeBox);
//        return boxArr;
//    }
//
//    @ApiOperation("查询预警")
//    @PostMapping("/getEarlyWarning")
//    public void getEarlyWarning(@RequestBody Integer Device_Id) {
////        ad_ApiMapper.insertTrainRecorder(nd_TrainRecoder);
////        Nd_WebSocketController myWebSocketHandler = new Nd_WebSocketController();
////        myWebSocketHandler.sendMessage("trackChange");
////        return  m;
//    }
}





